package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.dto.RequestParams;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import cn.itcast.hotel.vo.PageResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * @param requestParams
     * @description： 酒店搜索分页业务逻辑实现
     * @date：2024/3/22 16:13
     * @return：
     */
    @Override
    public PageResult search(RequestParams requestParams) throws IOException {
        //创建搜索请求对象
        SearchRequest request = new SearchRequest("hotel");
        buildDSL(requestParams, request);
        //发送查询请求，获取响应结果
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //解析响应结果
        return getPageResult(response);
    }

    /**
     * @description： 构造DSL参数
     * @date：2024/3/22 17:11
     * @return：
     **/
    private static void buildDSL(RequestParams requestParams, SearchRequest request) {
        String key = requestParams.getKey();//查询参数
        Integer page = requestParams.getPage();//查询页码
        Integer size = requestParams.getSize();//每页显示条数
        String sortBy = requestParams.getSortBy();//排序方式
        String brand = requestParams.getBrand();//品牌
        String city = requestParams.getCity();//城市
        String starName = requestParams.getStarName();//星级
        Integer maxPrice = requestParams.getMaxPrice();//最大价格值
        Integer minPrice = requestParams.getMinPrice();//最小价格值
        String location = requestParams.getLocation();//当前位置经纬度
        //构造查询请求参数
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (StringUtils.isEmpty(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        //城市条件
        if (!StringUtils.isEmpty(city)) {
            boolQuery.must(QueryBuilders.termQuery("city", city));

        }
        //品牌条件
        if (!StringUtils.isEmpty(brand)) {
            boolQuery.should(QueryBuilders.termQuery("brand", brand));

        }
        //星级条件
        if (!StringUtils.isEmpty(starName)) {
            boolQuery.filter(QueryBuilders.termQuery("starName", starName));

        }
        //最大价格
        if (!StringUtils.isEmpty(maxPrice)) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(maxPrice));

        }
        //最小价格
        if (!StringUtils.isEmpty(minPrice)) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice));

        }
        //距离排序
        if (!StringUtils.isEmpty(location)) {
            request.source().sort(SortBuilders
                    .geoDistanceSort("location", new GeoPoint(location))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS));
        }

        //算分控制
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD",true), //算分函数的过滤条件 满足条件才会加分
                                ScoreFunctionBuilders.weightFactorFunction(5)    //权重多少分
                        )
                }
        );
        //按照评价降序，价格升序排序
        if (sortBy.equals("score")){
            request.source().sort("score",SortOrder.DESC);
        }else if (sortBy.equals("price")){
            request.source().sort("price",SortOrder.ASC);
        }

        //高亮设置
        request.source().highlighter(
                new HighlightBuilder().field("name")
                        .requireFieldMatch(false)
        );
        //分页
        request.source().from((page - 1) * size).size(size);
        request.source().query(functionScoreQueryBuilder);
    }

    /**
     * @description： 解析响应结果
     * @date：2024/3/22 17:12
     * @return：
     **/
    private static PageResult getPageResult(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        //获取查询结果记录数
        long total = searchHits.getTotalHits().value;
        log.info("查询总记录数：total = {}", total);
        List<HotelDoc> hotelDocs = new ArrayList<>();
        //获取查询结果具体数据
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            //反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            //获取排序参数
            Object[] sortValues = hit.getSortValues();
            if (sortValues != null && sortValues.length > 0) {
                //获取距离
                Object sortValue = sortValues[0];
                if (sortValue != null) {
                    hotelDoc.setDistance(sortValue);
                }
            }
            //返回高亮参数给前端
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)){
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null){
                    String newName = highlightField.getFragments()[0].string();
                    hotelDoc.setName(newName);
                }
            }
            //将文档对象添加到集合中
            hotelDocs.add(hotelDoc);
        }
        //返回响应结果
        return PageResult.builder()
                .total(total)
                .hotels(hotelDocs)
                .build();
    }
}
